package com.example.recordingpen_datacollection.Utils.AIUtil;
import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;
import com.example.recordingpen_datacollection.result.exceptionhandler.BDxception;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@Slf4j
@Data
public class SSEListener extends EventSourceListener {

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    private ChatGlmDto chatGlmDto;

    private HttpServletResponse rp;

    private List<String> output = new ArrayList<>();

    public SSEListener(ChatGlmDto chatGlmDto, HttpServletResponse response) {
        this.chatGlmDto = chatGlmDto;
        this.rp = response;
    }

    public List<String> getOutput() {
        return output;
    }

    /**
     * {@inheritDoc}
     * 建立sse连接
     */
    @Override
    public void onOpen(final EventSource eventSource, final Response
            response) {
        if (rp != null) {
            rp.setContentType("text/event-stream");
            rp.setCharacterEncoding("UTF-8");
            rp.setStatus(200);
            log.info("建立sse连接..." + JSON.toJSONString(chatGlmDto));
        } else {
            log.info("客户端非sse推送" + JSON.toJSONString(chatGlmDto));
        }
    }

    /**
     * 事件
     *
     * @param eventSource
     * @param id
     * @param type
     * @param data
     */
    @Override
    public void onEvent(EventSource eventSource, String id, String type, String data) {
        //{"disable_search":false,"messages":[{"content":"深圳天气怎么样？","role":"user"}],"stream":true,"system":"Philips的AI助手","temperature":0.5}
        try {
//            Thread.sleep(100);
//            System.out.println(data +"-
            System.out.println(data +"67 "+ type);
            output.add(data);
            if ("finish".equals(type)) {
                log.info("请求结束{} {}", chatGlmDto.getMessageId(), output.toString());
            }
            if ("error".equals(type)) {
                log.info("{}: {}source {}", chatGlmDto.getMessageId(), data, JSON.toJSONString(chatGlmDto));
            }
            if (rp != null) {
                if ("\n".equals(data)) {
//                    rp.getWriter().write("event:" + type + "\n");
//                    rp.getWriter().write("id:" + chatGlmDto.getMessageId() + "\n");
                    rp.getWriter().write("data:\n\n");
                    rp.getWriter().flush();
                    System.out.println(1);
                } else {
                    String[] dataArr = data.split("\\n");
                    for (int i = 0; i < dataArr.length; i++) {
                        System.out.println(2);
//                        System.out.println(System.currentTimeMillis()+"---》发送时间戳");
                        if (i == 0) {
                            System.out.println("i == 0");
//                            rp.getWriter().write("event:" + type + "\n");
//                            rp.getWriter().write("id:" + chatGlmDto.getMessageId() + "\n");
                        }
                        if (i == dataArr.length - 1) {
                            System.out.println(dataArr[i]);
                            rp.getWriter().write("data:" + dataArr[i] + "\n\n");
                            rp.getWriter().flush();
                        } else {
                            System.out.println("else");
                            rp.getWriter().write("data:" + dataArr[i] + "\n");
                            rp.getWriter().flush();
                        }
                    }
                }

            }
        } catch (Exception e) {
            log.error("消息错误[" + JSON.toJSONString(chatGlmDto) + "]", e);
            countDownLatch.countDown();
            throw new RuntimeException(e);
        }

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onClosed(final EventSource eventSource) {
        log.info("sse连接关闭:{}", chatGlmDto.getMessageId());
        log.info("结果输出:{}" + output.size());

        countDownLatch.countDown();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onFailure(final EventSource eventSource, final Throwable t, final Response response) {
        log.error("使用事件源时出现异常... [响应22：{}]...", chatGlmDto.getMessageId());
        System.out.println(t);
        JSONObject jsonObject = null;
        try {
//            Object string =() response.body().string();
            jsonObject = JSONObject.parseObject(response.body().string());
//            if (rp != null) {
//                rp.getWriter().write("data:" + response.body().string() + "\n");
//                rp.getWriter().flush();
//            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        countDownLatch.countDown();
        throw new BDxception(jsonObject.getInteger("error_code"),jsonObject.getString("error_msg") );

    }



    public CountDownLatch getCountDownLatch() {
        System.out.println("倒数锁存器 getCountDownLatch");
        return this.countDownLatch;
    }



}

